//
//  MQAgentAruthViewController.m
//  meiquan
//
//  Created by hejingjin on 2017/10/28.
//  Copyright © 2017年 mq. All rights reserved.
//

#import "MQAgentAruthViewController.h"
#import "MQagentaruthview.h"
#import "MQBaseUserInfoModel.h"
#import "ZHPickView.h"
#import "MQadviews.h"
#import "MQAdmodels.h"
#import "NSString+Extension.h"
#import "MBProgressHUD+MJ.h"
#import <UShareUI/UShareUI.h>


@interface MQAgentAruthViewController ()<ZHPickViewDelegate>

@property(nonatomic,strong)MQagentaruthview *agentaruthview;

@property(nonatomic,strong)MQadviews *adviews;

@property(nonatomic,strong)MQAdmodels *admodels;

@property(nonatomic,strong)UIScrollView *bgview;
@end

@implementation MQAgentAruthViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"代理商授权";
    
    [self setUpMainInterface];
    
    [self getaddata];
    
}

-(void)getaddata{
    
    NSArray *array = @[@"page1",@"@page2",@"page3"];
    int x = arc4random() % 3;
    
    MQBaseUserInfoModel *userinfo = [MQBaseUserInfoModel shareInstant];
    [userinfo loadUserinfoFromSadeBox];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    
    [param setValue:userinfo.userId forKey:@"userId"];
    [param setValue:array[x] forKey:@"code"];
    [param setValue:@"page1" forKey:@"code"];
    
    [MQRequestTools POSTWithMethod:adv_index params:param success:^(id json) {
        
        NSDictionary *dic = [json valueForKey:@"data"];
        _admodels = [MQAdmodels mj_objectWithKeyValues:dic];
        if (_admodels.advId) {
            [_adviews.adimageviews sd_setImageWithURL:[NSURL URLWithString:_admodels.pic] placeholderImage:[UIImage imageNamed:@""]];
        }else{
            _adviews.bst_height = 0;
            _bgview.bst_y = NAVHEIGHT;
            
        }
        UITapGestureRecognizer *tapGesturRecognizer=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
        [_adviews addGestureRecognizer:tapGesturRecognizer];
        
    } failure:^(NSError *error) {
        
    }];
    
    
}

-(void)tapAction:(UITapGestureRecognizer *)obj{
    NSLog(@"%@",_admodels.url);
    MQAdDetailViewController *advc = [[MQAdDetailViewController alloc] init];
    advc.url = _admodels.url;
     advc.type = _admodels.type;
    [self.navigationController pushViewController:advc animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)setUpMainInterface{
    
 
    UIButton *btn = [[UIButton alloc] initWithFrame:(CGRectMake(0, 0, 40, 40))];
    [btn setTitle:@"分享" forState:(UIControlStateNormal)];
    [btn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    [btn addTarget:self action:@selector(sharePress) forControlEvents:(UIControlEventTouchUpInside)];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    self.navigationItem.rightBarButtonItem = rightItem;

    self.view.backgroundColor = BSTColorFromRGB(0xefefef);

    
    _adviews = [MQadviews loadadviews];
    _adviews.bst_x = 0;
    _adviews.bst_width = BSTScreenW;
    _adviews.bst_height = 70 *Persion;
    _adviews.bst_y = NAVHEIGHT;
    [self.view addSubview:_adviews];
    
    UIScrollView *bgview = [[UIScrollView alloc] initWithFrame:CGRectMake(0, NAVHEIGHT + 70 * Persion, BSTScreenW, BSTScreenH - NAVHEIGHT - 70 * Persion)];
    _bgview = bgview;
    
    MQagentaruthview *agentaruthview = [MQagentaruthview loadagentaruthview];
    
    agentaruthview.bst_x = 0;
    agentaruthview.bst_y = 0;
    agentaruthview.bst_width = BSTScreenW;
    agentaruthview.bst_height = 1111;
    _agentaruthview = agentaruthview;
    _agentaruthview.submitbutton.layer.cornerRadius = 3.f;
    _agentaruthview.submitbutton.layer.masksToBounds = YES;
    _agentaruthview.passbutton.layer.cornerRadius = 3.f;
    _agentaruthview.nopassbutton.layer.cornerRadius = 3.f;
    _agentaruthview.passbutton.layer.masksToBounds = YES;
    _agentaruthview.nopassbutton.layer.masksToBounds = YES;
    _agentaruthview.productimageview.image = [UIImage imageNamed:@"plasc"];
    [_agentaruthview.submitbutton addTarget:self action:@selector(submitbuttonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [_agentaruthview.passbutton addTarget:self action:@selector(passbuttonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [_agentaruthview.nopassbutton addTarget:self action:@selector(nopassbuttonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [bgview addSubview:agentaruthview];
    [bgview setContentSize:CGSizeMake(BSTScreenW, 1111 + 70 * Persion)];
    if ([_model.status integerValue] ==3) {
            _agentaruthview.submitbutton.hidden = NO;
            _agentaruthview.passbutton.hidden = YES;
            _agentaruthview.nopassbutton.hidden = YES;
            //
            
            _agentaruthview.pweixin.enabled = NO;
            _agentaruthview.canpingma.enabled = NO;
            _agentaruthview.dailidengji.enabled = NO;
            _agentaruthview.zhenshixinm.enabled = NO;
            _agentaruthview.wodeweixinhao.enabled = NO;
            
            
            
            _agentaruthview.eamil.enabled = NO;
            _agentaruthview.shopone.enabled = NO;
            _agentaruthview.shoptwo.enabled = NO;
            _agentaruthview.shopthree.enabled = NO;
            _agentaruthview.countone.enabled = NO;
            _agentaruthview.counttwo.enabled = NO;
            _agentaruthview.coutthtee.enabled = NO;
            
            _agentaruthview.idcard.enabled = NO;
            _agentaruthview.zhenshixinm.enabled  = NO;
            _agentaruthview.tuijianren.enabled = NO;
            _agentaruthview.beizhu.editable = NO;
            
            
            
            
        }else{
            if ([_model.status integerValue] ==0 && [_model.vstatus integerValue] ==0) {
                _agentaruthview.submitbutton.hidden = YES;
                _agentaruthview.passbutton.hidden = NO;
                _agentaruthview.nopassbutton.hidden = NO;
//                不可编辑
                _agentaruthview.pweixin.enabled = NO;
                _agentaruthview.canpingma.enabled = NO;
                _agentaruthview.dailidengji.enabled = NO;
                _agentaruthview.zhenshixinm.enabled = NO;
                _agentaruthview.wodeweixinhao.enabled = NO;
                
                
                
                _agentaruthview.eamil.enabled = NO;
                _agentaruthview.shopone.enabled = NO;
                _agentaruthview.shoptwo.enabled = NO;
                _agentaruthview.shopthree.enabled = NO;
                _agentaruthview.countone.enabled = NO;
                _agentaruthview.counttwo.enabled = NO;
                _agentaruthview.coutthtee.enabled = NO;
                
                _agentaruthview.idcard.enabled = NO;
                _agentaruthview.zhenshixinm.enabled  = NO;
                _agentaruthview.tuijianren.enabled = NO;
                _agentaruthview.beizhu.editable = YES;
                
            }else{
                _agentaruthview.submitbutton.hidden = YES;
                _agentaruthview.passbutton.hidden = YES;
                _agentaruthview.nopassbutton.hidden = YES;
                _agentaruthview.bst_height = MAX_Y(_agentaruthview.beizhu.frame) +20;
                [bgview setContentSize:CGSizeMake(BSTScreenW, _agentaruthview.bst_height)];
                //                不可编辑
                _agentaruthview.pweixin.enabled = NO;
                _agentaruthview.canpingma.enabled = NO;
                _agentaruthview.dailidengji.enabled = NO;
                _agentaruthview.zhenshixinm.enabled = NO;
                _agentaruthview.wodeweixinhao.enabled = NO;
                
                
                
                _agentaruthview.eamil.enabled = NO;
                _agentaruthview.shopone.enabled = NO;
                _agentaruthview.shoptwo.enabled = NO;
                _agentaruthview.shopthree.enabled = NO;
                _agentaruthview.countone.enabled = NO;
                _agentaruthview.counttwo.enabled = NO;
                _agentaruthview.coutthtee.enabled = NO;
                
                _agentaruthview.idcard.enabled = NO;
                _agentaruthview.zhenshixinm.enabled  = NO;
                _agentaruthview.tuijianren.enabled = NO;
                _agentaruthview.beizhu.editable = NO;
            }
        }
//        
//    }else{
//        _agentaruthview.submitbutton.hidden = YES;
//        _agentaruthview.passbutton.hidden = YES;
//        _agentaruthview.nopassbutton.hidden = YES;
//        
//        _agentaruthview.pweixin.enabled = NO;
//        _agentaruthview.canpingma.enabled = NO;
//        _agentaruthview.dailidengji.enabled = NO;
//        _agentaruthview.zhenshixinm.enabled = NO;
//        _agentaruthview.wodeweixinhao.enabled = NO;
//        
//        
//        
//        _agentaruthview.eamil.enabled = NO;
//        _agentaruthview.shopone.enabled = NO;
//        _agentaruthview.shoptwo.enabled = NO;
//        _agentaruthview.shopthree.enabled = NO;
//        _agentaruthview.countone.enabled = NO;
//        _agentaruthview.counttwo.enabled = NO;
//        _agentaruthview.coutthtee.enabled = NO;
//        
//        _agentaruthview.idcard.enabled = NO;
//        _agentaruthview.zhenshixinm.enabled  = NO;
//        _agentaruthview.tuijianren.enabled = NO;
//        _agentaruthview.beizhu.editable = NO;
//        
//    }
    
    [self.view addSubview:bgview];
    
    
    
    _agentaruthview.pweixin.text = _model.parentAgent.telephone;
    _agentaruthview.canpingma.text = _model.code;
    _agentaruthview.dailidengji.text = _model.level;
    _agentaruthview.zhenshixinm.text = _model.realName;
    _agentaruthview.wodeweixinhao.text = _model.weixin;
    
    
    
    _agentaruthview.eamil.text = _model.email;
    _agentaruthview.shopone.text = _model.shop1;
    _agentaruthview.shoptwo.text = _model.shop2;
    _agentaruthview.shopthree.text = _model.shop3;
    _agentaruthview.countone.text = _model.account1;
    _agentaruthview.counttwo.text = _model.account2;
    _agentaruthview.coutthtee.text = _model.account3;
    
    _agentaruthview.idcard.text = _model.cardId;
    _agentaruthview.zhenshixinm.text  = _model.realName;
    _agentaruthview.tuijianren.text = _model.referrer;
//    _agentaruthview.beizhu.editable = _model.;
    
}

-(void)sharePress{
    MQBaseUserInfoModel *model = [MQBaseUserInfoModel shareInstant];
    [model loadUserinfoFromSadeBox];
    
    [MBProgressHUD showMessage:@"正在获取数据，请稍后..."];
    
    [MQRequestTools POSTWithMethod:agent_levels params:@{@"adminId": model.userId} success:^(id json) {
        [MBProgressHUD hideHUD];
        NSMutableArray *ary = [NSMutableArray array];
        for (NSDictionary *dic in json[@"data"]) {
            [ary addObject:dic[@"name"]];
        }
        ZHPickView *picker = [[ZHPickView alloc] initPickviewWithArray:ary isHaveNavControler:NO];
        picker.delegate = self;
        [self.view addSubview:picker];
        
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUD];
        [iToastUtil displayMsg:@"网路连接失败"];
    }];
    
}

-(void)toobarDonBtnHaveClick:(ZHPickView *)pickView resultString:(NSString *)resultString
{
    MQBaseUserInfoModel *model = [MQBaseUserInfoModel shareInstant];
    [model loadUserinfoFromSadeBox];

    NSDictionary *params = @{
                          @"levelName":resultString,
                          @"account" : model.username,
                          @"code": @"5ftd6n",
                          @"codeName": @"meiquan01-01"
                          };
    [MBProgressHUD showMessage:@"正在获取二维码，请稍后..."];

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSString *paramstr = @"";
    if (params) {
        
        
        NSArray *keyarray = [params allKeys];
        //        [keyarray sortUsingComparator: ^NSComparisonResult (NSString *str1, NSString *str2) {
        //            return [str1 compare:str2];
        //        }];
        NSArray *key = [NSArray array];
        key =  [keyarray sortedArrayUsingComparator:^NSComparisonResult (NSString *str1, NSString *str2) {
            return [str1 compare:str2];
        }];
        
        //        NSArray *values = [params allValues];
        for (NSString *str in key) {
            paramstr = [paramstr stringByAppendingString:[params valueForKey:str]];
        }
    }
    
    
    MQBaseUserInfoModel *userinfo = [MQBaseUserInfoModel shareInstant];
    [userinfo loadUserinfoFromSadeBox];
    
    if ([userinfo.userId isEqualToString:@""] || !userinfo.userId) {
        
    }else{
        
        NSString *sign = [MQHmacUtils hmac:paramstr withKey:userinfo.token];
        [manager.requestSerializer setValue:userinfo.userId forHTTPHeaderField:@"userId"];
        [manager.requestSerializer setValue:sign forHTTPHeaderField:@"sign"];
    }
    [manager GET:@"http://app.52meiquan.com/qrCoder/createShare" parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUD];
        UIImage *img = [UIImage imageWithData:responseObject];
            //显示分享面板
            [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
    
                //创建分享消息对象
                UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
                UMShareImageObject *shareObject = [[UMShareImageObject alloc] init];
                shareObject.shareImage = img;
                //分享消息对象设置分享内容对象
                messageObject.shareObject = shareObject;
    
                //调用分享接口
                [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
    
                }];
            }];

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUD];
        [iToastUtil displayMsg:@"网路连接失败"];

    }];
    
}

//重新上传
-(void)submitbuttonPressed:(UIButton *)sender{
 
    
    NSString *shangji = _agentaruthview.pweixin.text;
    NSString *wodeweixin = _agentaruthview.wodeweixinhao.text;
    NSString *tuijianren = _agentaruthview.tuijianren.text;
    NSString *canpingma = _agentaruthview.canpingma.text;
    NSString *dailidengji = _agentaruthview.dailidengji.text;
    NSString *zhenshixinming = _agentaruthview.zhenshixinm.text;
    NSString *shenfenzheng = _agentaruthview.idcard.text;
    NSString *youxiang = _agentaruthview.eamil.text;
    
    NSString *shopone = _agentaruthview.shopone.text;
    NSString *count1 = _agentaruthview.countone.text;
    NSString *shop2 = _agentaruthview.shoptwo.text;
    NSString *count2 = _agentaruthview.counttwo.text;
    NSString *shop3 =  _agentaruthview.shopthree.text;
    NSString *count3 = _agentaruthview.coutthtee.text;
    
    if ([NSString isBlankString:shangji]) {
        [iToastUtil displayMsg:@"请输入上级微信号"];
        return;
    }
    if ([NSString isBlankString:wodeweixin]) {
        [iToastUtil displayMsg:@"请输入我的微信号"];
        return;
    }
    if ([NSString isBlankString:tuijianren]) {
        [iToastUtil displayMsg:@"请输入推荐人"];
        return;
    }
    if ([NSString isBlankString:canpingma]) {
        [iToastUtil displayMsg:@"请输入产品码"];
        return;
    }
    if ([NSString isBlankString:dailidengji]) {
        [iToastUtil displayMsg:@"请输入代理等级"];
        return;
    }
    if ([NSString isBlankString:zhenshixinming]) {
        [iToastUtil displayMsg:@"请输入真实姓名"];
        return;
    }
    if ([NSString isBlankString:shenfenzheng]) {
        [iToastUtil displayMsg:@"请输入身份证"];
        return;
    }
    if ([NSString isBlankString:youxiang]) {
        [iToastUtil displayMsg:@"请输入邮箱"];
        return;
    }
    if ([NSString isBlankString:shopone]) {
        [iToastUtil displayMsg:@"请输入店铺名称一"];
        return;
    }
    if ([NSString isBlankString:count1]) {
        [iToastUtil displayMsg:@"请输入店铺一账号"];
        return;
    }
    if ([NSString isBlankString:shop2]) {
        [iToastUtil displayMsg:@"请输入店铺名称二"];
        return;
    }
    if ([NSString isBlankString:count2]) {
        [iToastUtil displayMsg:@"请输入店铺二账号"];
        return;
    }
    if ([NSString isBlankString:shop3]) {
        [iToastUtil displayMsg:@"请输入店铺名称三"];
        return;
    }
    if ([NSString isBlankString:count3]) {
        [iToastUtil displayMsg:@"请输入店铺三账号"];
        return;
    }

    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    MQBaseUserInfoModel *userinfo = [MQBaseUserInfoModel shareInstant];
    [userinfo loadUserinfoFromSadeBox];
    [param setValue:userinfo.userId forKey:@"userId"];
    [param setValue:_model.ID forKey:@"id"];
    

    
    [param setValue:shangji forKey:@"parent"];
    [param setValue:wodeweixin forKey:@"weixin"];
    [param setValue:tuijianren forKey:@"referrer"];
    [param setValue:canpingma forKey:@"code"];
    [param setValue:dailidengji forKey:@"level"];
    [param setValue:zhenshixinming forKey:@"realName"];
    [param setValue:shenfenzheng forKey:@"cardId"];
    [param setValue:youxiang forKey:@"email"];
    [param setValue:shopone forKey:@"shop1"];
    [param setValue:count1 forKey:@"account1"];
    [param setValue:shop2 forKey:@"shop2"];
    [param setValue:count2 forKey:@"account2"];
    [param setValue:shop3 forKey:@"shop3"];
    [param setValue:count3 forKey:@"account3"];
    
    
    [MQRequestTools POSTWithMethod:agent_update params:param success:^(id json) {
        [iToastUtil displayMsg:@"更新成功"];
        [self.navigationController popViewControllerAnimated:YES];
    } failure:^(NSError *error) {
        
    }];
    
    
}

-(void)passbuttonPressed:(UIButton *)sender{
    
    NSString *reson = _agentaruthview.beizhu.text;
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    MQBaseUserInfoModel *userinfo = [MQBaseUserInfoModel shareInstant];
    [userinfo loadUserinfoFromSadeBox];
    [param setValue:userinfo.userId forKey:@"userId"];
    [param setValue:_model.ID forKey:@"agentId"];
    [param setValue:reson forKey:@"reason"];
    
    
    [MQRequestTools POSTWithMethod:agent_pass params:param success:^(id json) {
        
        [self.navigationController popViewControllerAnimated:YES];
    } failure:^(NSError *error) {
        
    }];
    
    
    
}
-(void)nopassbuttonPressed:(UIButton *)sender{
    NSString *reson = _agentaruthview.beizhu.text;
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    
    MQBaseUserInfoModel *userinfo = [MQBaseUserInfoModel shareInstant];
    [userinfo loadUserinfoFromSadeBox];
    
    [param setValue:userinfo.userId forKey:@"userId"];
    [param setValue:_model.ID forKey:@"agentId"];
    [param setValue:reson forKey:@"reason"];
    
    
    [MQRequestTools POSTWithMethod:agent_notPass params:param success:^(id json) {
        
    } failure:^(NSError *error) {
        
    }];
}
@end
